﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ortodoctor.gridComponent;
using System.Data;
using Ortodoctor.modelo;
using Ortodoctor.Componentes;

namespace Ortodoctor.Funcionario
{
    public partial class CadastroClinica : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (Session["USUARIO"] == null)
            //    Response.Redirect("Login.aspx");
            //if(Session["GRID_CLINICA"] == null)
            //{
            //    ModeloClinica model = new ModeloClinica();
            //    Grid grid = new Grid(model.getAll(), "id_clinica");
            //    Session["GRID_CLINICA"] = grid;
            //}
            if (Session["USUARIO"] == null)
                Response.Redirect("Login.aspx");
            if (Session["USUARIO_ACESSO"].ToString().CompareTo("2") == 0)
            {
               
                ModeloClinica model = new ModeloClinica();
                Grid grid = new Grid(model.getAll(), "id_clinica");
                Session["GRID_CLINICA"] = grid;
            }
            else
            {
                permissao.Value = "Você não tem permissão para visualizar essa página";
            }
        }

        [WebMethod]
        public static string getDados(string page, string rp, string sortname, string sortorder, string query, string qtype)
        {
            Grid grid = ((Grid)HttpContext.Current.Session["GRID_CLINICA"]);
            grid.page = Convert.ToInt32(page);
            DataTable dt = grid.dados.Clone();

            if (string.IsNullOrEmpty(query))
            {
                int numeroItensPagina = Convert.ToInt32(rp);
                int numeroPagina = Convert.ToInt32(page);
                int inicio = numeroItensPagina * (numeroPagina - 1);

                for (int i = inicio; i < inicio + numeroItensPagina && i < grid.dados.Rows.Count; ++i)
                {
                    DataRow dr = dt.NewRow();
                    foreach (DataColumn dc in dt.Columns)
                        dr[dc.ColumnName] = grid.dados.Rows[i][dc.ColumnName];

                    dt.Rows.Add(dr);
                }
                if (dt.Rows.Count > 0)
                {
                    dt.DefaultView.Sort = sortname + " " + sortorder;
                    dt = dt.DefaultView.ToTable();
                }
            }
            else
            {
                dt = grid.dados.Copy();
                dt.DefaultView.RowFilter = string.Format("[{0}] like '%{1}%'", qtype, query);
                dt = dt.DefaultView.ToTable();
            }
            return grid.getDadosToJson(dt);
        }

        [WebMethod]
        public static string addToTable(string dados)
        {
            Grid grid = ((Grid)HttpContext.Current.Session["GRID_CLINICA"]);

            modeloEndereco endereco = new modeloEndereco();
            string[] strEnd = dados.Split('|');
            int p=0;
            try
            {
                p = Convert.ToInt32(strEnd[1]);
            } catch (Exception e) { p = 0; }

            Endereco end = new Endereco(-1,
                                         strEnd[0].ToString(),
                                         p,
                                         strEnd[3].ToString(),
                                         strEnd[2].ToString(),
                                         strEnd[4].ToString(),
                                         strEnd[5].ToString());

            int id = endereco.insert(end);
            end.IdEndereco = id;
            ModeloClinica clinicaModel = new ModeloClinica();
            Clinica clinica = new Clinica(-1, end);
            int idClinica = clinicaModel.insert(clinica);
            
            DataRow dr = grid.dados.NewRow();
            dr["id_clinica"] = idClinica.ToString();
            dr["cidade"] = clinica.Endereco.Cidade;
            dr["rua"] = clinica.Endereco.Rua;
            dr["numero"] = clinica.Endereco.Numero;
            
            grid.dados.Rows.Add(dr);
            grid.total++;
            HttpContext.Current.Session["GRID_CLINICA"] = grid;
            return "adicionou";
        }

        [WebMethod]
        public static string editTable(int id, string dados)
        {
            Grid grid = ((Grid)HttpContext.Current.Session["GRID_CLINICA"]);

            string[] strEnd = dados.Split('|');

            int p = 0;int p1 = 0;
            try
            {
                p = Convert.ToInt32(HttpContext.Current.Session["ENDERECO_CLINICA"]);
            }
            catch (Exception e) { p = 0; }

            try
            {
                p1 = Convert.ToInt32(strEnd[1]);
            }
            catch (Exception e) { p1 = 0; }

            modeloEndereco endereco = new modeloEndereco(); 
            Endereco end = new Endereco(p, 
                                         strEnd[0].ToString(),
                                         p1, 
                                         strEnd[3].ToString(), 
                                         strEnd[2].ToString(), 
                                         strEnd[4].ToString(),
                                         strEnd[5].ToString());
            endereco.update(end);

            ModeloClinica client = new ModeloClinica();
            Clinica Clinica = new Clinica(id,
                                          end);
            client.update(Clinica);

            DataRow[] srw = grid.dados.Select("[id_Clinica] = " + id.ToString());
            DataRow dr = srw[0];
            dr["rua"] = end.Rua;
            dr["cidade"] = end.Cidade;
            dr["numero"] = end.Numero;
            srw[0] = dr;
            HttpContext.Current.Session["GRID_CLINICA"] = grid;
            return "editou";
        }

        [WebMethod]
        public static string deleteFromTable(int id)
        {
            Grid grid = ((Grid)HttpContext.Current.Session["GRID_CLINICA"]);
            grid.deleteFromTable(id);
            ModeloClinica clinica = new ModeloClinica();
            clinica.delete(id);
            HttpContext.Current.Session["GRID_CLINICA"] = grid;
            return "removeu";
        }

        [WebMethod]
        public static string getDataFromClinica(int id)
        {
            ModeloClinica client = new ModeloClinica();
            DataTable dt = client.getClinica(id);
            string retorno = "";
            
            if(dt.Rows.Count > 0)
            {
                retorno += dt.Rows[0]["rua"].ToString() + "|";
                retorno += dt.Rows[0]["numero"].ToString() + "|";
                retorno += dt.Rows[0]["cidade"].ToString() + "|";
                retorno += dt.Rows[0]["bairro"].ToString() + "|";
                retorno += dt.Rows[0]["uf"].ToString() + "|";
                retorno += dt.Rows[0]["cep"].ToString();
                HttpContext.Current.Session["ENDERECO_CLINICA"] = dt.Rows[0]["id_endereco"];
            }
            
            return retorno;
        }
    }
}